<template>
  <el-dialog :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" :close-on-click-modal="false" :visible.sync="visible" class="cu-dialog cu-dialog_center" lock-scroll width="900px" v-loading="loading">
    <el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
      <!-- <el-form-item label-width="0">
        <groupTitle content-identity="left" content="基础信息"></groupTitle>
      </el-form-item> -->
      <el-row :gutter="5" type="flex" style="flex-wrap: wrap">
        <el-col :span="12">
          <el-form-item label="校区" prop="campusId">
            <el-select v-model="dataForm.campusId" placeholder="请选择" clearable required filterable :style="{ width: '100%' }" @change="hanldChangeCampus">
              <el-option v-for="(item, index) in campusOptions" :key="index" :label="item.fullName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="赠送帐号" prop="account">
            <el-input-number v-model="dataForm.account" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input-number>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker v-model="dataForm.startDate" placeholder="请选择" clearable required type="date" format="yyyy-MM-dd" value-format="timestamp" :style="{ width: '100%' }"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止日期" prop="endDate">
            <el-date-picker v-model="dataForm.endDate" placeholder="请选择" clearable required :style="{ width: '100%' }" type="date" format="yyyy-MM-dd" value-format="timestamp"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应收金额" prop="receivable">
            <el-input v-model="dataForm.receivable" @blur="hanldBlurReceivalbeOrActual" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实收金额" prop="actual">
            <el-input v-model="dataForm.actual" @change="hanldBlurReceivalbeOrActual" required clearable :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收款日期" prop="signingDate">
            <el-date-picker v-model="dataForm.signingDate" placeholder="请选择" clearable required :style="{ width: '100%' }" type="date" format="yyyy-MM-dd" value-format="timestamp"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="0">
            <groupTitle content-identity="left" content="赠送清单"></groupTitle>
            <el-table :data="dataForm.giveList" size="mini" empty-text="点击下方“添加”按钮">
              <el-table-column type="index" width="50" label="序号" align="center" />
              <el-table-column prop="goodsId" label="赠送商品" header-align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.goodsId" placeholder="请选择商品" filterable clearable @change="getGoodsTypeOptions(scope)">
                    <el-option v-for="item in goodsOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="standards" label="商品规格" header-align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.standards" placeholder="请选择规格" filterable clearable>
                    <el-option v-for="item in goodsTypeOptions" :key="item.value" :label="item.label + '/' + item.unitDescribe" :value="item.value"></el-option>
                  </el-select>
                  <!--                  <el-input v-model="scope.row.standards" placeholder="请输入商品规格" clearable :disabled="judgeWrite('giveList')"></el-input>-->
                </template>
              </el-table-column>
              <el-table-column prop="num" label="赠送数量" align="center" width="140">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.num" placeholder="请选择赠送数量" clearable></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="needShip" label="需要发货" align="center" width="80">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.needShip"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="备注" header-align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.description" placeholder="请输入备注" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="50">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" class="cu-table-delBtn" @click="handleDelGiveList(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-actions" @click="addHandleGiveList()">
              <el-button type="text" icon="el-icon-plus">添加</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="支付情况" prop="isPayed">
            <el-radio-group v-model="dataForm.isPayed" required :style="{}">
              <el-radio v-for="(item, index) in isPayedOptions" :key="index" :label="item.enCode">{{ item.fullName }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="续费政策" prop="policy">
            <el-input v-model="dataForm.policy" placeholder="请输入" show-word-limit :style="{ width: '100%' }" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否发送邮件" prop="emailCC">
            <el-checkbox v-model="dataForm.isEmail"></el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="收件人" prop="emailTo">
            <org-select ref="user-org" buttonType="button" v-model="dataForm.emailTo" title="添加用户" class="mb-10" @change="onOrgChange" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail" :loading="loading">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import request from '@/utils/request'
import dayjs from 'dayjs'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import { getCampusSelector } from '@/api/campus/campus'
import OrgSelect from '@/components/Process/OrgSelect'
import custom from '@/utils/custom'
import { getGoodsCategory, getGoodsType } from '@/api/services/goods'
export default {
  components: { OrgSelect },
  props: [],
  data() {
    return {
      loading: false,
      visible: false,
      isDetail: false,
      dataForm: {
        id: '',
        isPayed: 'No',
        campusId: undefined,
        startDate: undefined,
        endDate: undefined,
        receivable: undefined,
        actual: undefined,
        policy: undefined,
        createUserId: undefined,
        createTime: undefined,
        isEmail: false,
        signingDate: undefined,
        emailTo: [],
        emailCC: undefined,
        giveList: undefined
      },
      rules: {
        campusId: [
          {
            required: true,
            message: '请输入校区',
            trigger: 'change'
          }
        ],
        startDate: [
          {
            required: true,
            message: '请选择服务开始日期',
            trigger: 'change'
          }
        ],
        endDate: [
          {
            required: true,
            message: '请选择服务截止日期',
            trigger: 'change'
          }
        ],
        receivable: [
          {
            required: true,
            message: '请输入应收金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        account: [
          {
            required: true,
            message: '请输入赠送帐号数量',
            trigger: 'blur'
          }
        ],
        actual: [
          {
            required: true,
            message: '请输入应收金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        emailTo: [
          {
            required: true,
            message: '请选择邮件的收件人',
            trigger: 'change'
          }
        ]
      },
      campusOptions: [],
      goodsOptions: [],
      goodsTypeOptions: [],
      isPayedOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getisPayedOptions()
    this.getCampusSelector()
  },
  mounted() {
    getGoodsCategory().then(res => {
      this.goodsOptions = res.data
    })
  },
  methods: {
    getGoodsTypeOptions(scope) {
      scope.row.standards = undefined
      this.goodsTypeOptions = []
      getGoodsType(scope.row.goodsId).then(res => {
        this.goodsTypeOptions = res.data
      })
    },
    handleDelGiveList(index) {
      this.dataForm.giveList.splice(index, 1)
    },
    addHandleGiveList() {
      let item = {
        goodsId: undefined,
        standards: undefined,
        num: 0,
        needShip: 0,
        description: undefined
      }
      this.dataForm.giveList = this.dataForm.giveList || []
      this.dataForm.giveList.push(item)
    },
    getisPayedOptions() {
      getDictionaryDataSelector('PayStatus').then(res => {
        this.isPayedOptions = res.data.list.filter(o => o.enCode != 'PartialNo' && o.enCode != 'Refunded' && o.enCode != 'No')
      })
    },
    getCampusSelector() {
      getCampusSelector().then(res => {
        this.campusOptions = this.isDetail ? res.data : res.data.filter(o => o.status != 'colse')
      })
    },

    onOrgChange(data) {
      this.dataForm.emailTo = data
    },

    goBack() {
      this.$emit('refresh')
    },
    addInit(row) {
      this.visible = true
      this.loading = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (row.id) {
          this.dataForm.campusId = row.id || ''
          this.dataForm.receivable = row.renewal
          this.dataForm.startDate = custom.timestamp(dayjs(row.endDate).add(1, 'day'))
          this.dataForm.endDate = custom.timestamp(dayjs(row.endDate).add(1, 'year'))

          console.log('add', row)
          this.initEmailTo(row)
          this.loading = false
        }
      })
    },
    updateInit(row) {
      this.visible = true
      this.loading = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (row.id) {
          request({
            url: '/api/campus/contract/last/' + row.id,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data
            if (!res.data.emailTo) {
              console.log('update', rowm)
            }
          })
        }
        this.loading = false
      }).catch(err => {
        this.visible = false
        this.loading = false
      })
    },
    hanldChangeCampus(value) {
      request({
        url: `api/campus/${value}`,
        method: 'get'
      }).then(res => {
        this.dataForm.receivable = res.data.renewal
        this.dataForm.startDate = custom.timestamp(dayjs(res.data.endDate).add(1, 'day'))
        this.dataForm.endDate = custom.timestamp(dayjs(res.data.endDate).add(1, 'year'))
      })
    },
    initEmailTo(campus) {
      let emailTo = ['433118678402204933', '433117269455799557', '416750280923677957', '416750736257320197', '381956723331564805', '423653212629763333', '416750360632231173', '396078644641924357', '416750479951791365', '416752342017246469', '433119597265159429', '370757840840688901', '416750440911209733', '519711074023376133', '433108138439214341']
      if (campus.company == '河北分公司') {
        emailTo.push('416749733969659141')
        emailTo.push('492107727120631045')
      } else if (campus.company == '山东分公司') {
        emailTo.push('720164055167272197')
        emailTo.push('416748329951560965')
      } else if (campus.company == '西安分公司') {
        emailTo.push('720164338505090309')
        emailTo.push('416748748413076741')
      }
      this.onOrgChange(emailTo)
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        if (index === 1) {
          sums[index] = ''
          return
        }
        if (index === 3) {
          sums[index] = ''
          return
        }
        if (index === 4) {
          sums[index] = ''
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              this.dataForm.actual = prev + curr
              this.hanldBlurReceivalbeOrActual()
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 元'
        } else {
          sums[index] = 'N/A'
        }
      })

      return sums
    },
    hanldBlurReceivalbeOrActual() {
      if (this.dataForm.receivable <= this.dataForm.actual) {
        this.dataForm.isPayed = 'Yes'
      } else if (this.dataForm.actual == 0) {
        this.dataForm.isPayed = 'No'
      } else if (this.dataForm.receivable > this.dataForm.actual) {
        this.dataForm.isPayed = 'PartialYes'
      } else {
        this.$message({
          message: '请再次确认实收金额，如无误请忽略。',
          type: 'warning',
          duration: 3000
        })
      }
    },
    dataFormSubmit() {
      // 防连点
      this.searchTimer && clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.$refs['elForm'].validate(valid => {
          if (valid) {
            this.loading = true
            if (!this.dataForm.id) {
              request({
                url: `/api/campus/contract`,
                method: 'post',
                data: this.dataForm
              }).then(res => {
                this.loading = false
                this.$message({
                  message: res.msg,
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    ;(this.visible = false), this.$emit('refresh', true)
                  }
                })
              })
            } else {
              request({
                url: '/api/campus/contract/' + this.dataForm.id,
                method: 'PUT',
                data: this.dataForm
              }).then(res => {
                // this.loading = false
                this.$message({
                  message: res.msg,
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refresh', true)
                  }
                })
              })
            }
          }
        })
      }, 300)
    }
  }
}
</script>
